package com.sumainfor.pc.market.service.tenant.impl;

import com.alibaba.fastjson.JSONObject;
import com.sumainfor.common.config.RedisUtils;
import com.sumainfor.common.entity.TemplateData;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.Jsapi_ticketUtil;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.common.wechat.WeChatConfig;
import com.sumainfor.pc.market.dao.tenant.TenRoomMapper;
import com.sumainfor.pc.market.feign.EpcFeign.EpcFeign;
import com.sumainfor.pc.market.feign.GmioFeign.GmioFeign;
import com.sumainfor.pc.market.feign.Zfeign.ZwxTenantFeign;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.NoTransactionException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Meng
 * @ClassName TenRoomService
 * @date 2020/1/2 17:00
 * @description: TODO
 */
@Service
public class TenRoomService implements Serializable {
    private ReentrantLock lock = new ReentrantLock(false);

    Logger log = LoggerFactory.getLogger(TenRoomService.class);

    @Autowired
    TenRoomMapper tenRoomMapper;

    @Autowired
    EpcFeign epcFeign;

    @Autowired
    RedisUtils redisUtils;
    @Autowired
    ZwxTenantFeign zwxTenantFeign;

    @Autowired
    GmioFeign gmioFeign;

    /**
     * 修改智能门锁密码的付款方式
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateMiMaType(Map<String,Object> params){
     JsonResult result = new JsonResult();

     lock.lock();
        try {
            Map<String,Object> PaIdMap = tenRoomMapper.getPaIdRoom(params);
            Map<String,Object> TenXinMap = new HashMap<>();
            TenXinMap.put("TenId",params.get("TenId"));
            TenXinMap.put("HouId",params.get("HouId"));
            JsonResult tenResult = zwxTenantFeign.getTenId(PaIdMap);
            Map<String,Object> tenMap = (Map<String, Object>) tenResult.get("result");
            params.put("phone",tenMap.get("TenPhone"));//租客手机号
            params.put("openid",tenMap.get("uopid"));//微信用户id

            Map<String,Object> getRoomBillMap = gmioFeign.getRoomBill(params);
            params.put("EndTime",getRoomBillMap.get("EndTime"));

            //根据房源编号获取智能设备
            epcFeign.getTenRoom(params);

    JsonResult epcResult = epcFeign.getTenRoom(TenXinMap);
    List<Map<String,Object>> epcIdenList = (List<Map<String, Object>>) epcResult.get("result");






            List<Map<String,Object>> identifierList = new ArrayList<>();
            if (MapUtils.getString(PaIdMap,"IntelligentRoom")!=null&&!MapUtils.getString(PaIdMap,"IntelligentRoom").equals("")){
                String IntelligentRoom = MapUtils.getString(PaIdMap,"IntelligentRoom");
                String IntelligentRooms = IntelligentRoom.substring(0,IntelligentRoom.length()-1);
                String[] arr1 = IntelligentRooms.split(",");
                for(String arrStr:arr1){
                    Map<String,Object> identMap = new HashMap<>();
                    identMap.put("Intelligent",PaIdMap.get("IntelligentType"));//锁类型
                    identMap.put("Identifier",arrStr.substring(0,arrStr.indexOf(":")));//锁编号
                    identMap.put("CodeId",arrStr.substring(arrStr.indexOf(":")+1));//钥匙
                    identifierList.add(identMap);
                }
            }

            //组装维修推送参数
            Map<String,Object> weiMap=new HashMap<String,Object>();
            weiMap.put("keyword1",new TemplateData(PaIdMap.get("Province").toString()+
                    PaIdMap.get("City").toString()+
                    PaIdMap.get("District").toString()+
                    PaIdMap.get("Street").toString()+
                    PaIdMap.get("Address").toString()+
                    PaIdMap.get("Road").toString()+"路"+
                    PaIdMap.get("BuilDing").toString()+"楼"+
                    PaIdMap.get("Room").toString()+"室"
                    ,"#4876FF"));//房源地址
            weiMap.put("first", new TemplateData("欢迎入住唐巢公寓，您的开门密码如下" +
                    "在门锁按键输入'密码+#'后便可开门", "#4876FF"));


            if(identifierList.size()>0){//有智能设备
                //先解除原来的蓝牙密码.改为发送键盘密码
                //修改智能门锁周期
                for (Map<String,Object> InteMap:identifierList){
                    //Intelligent 0.蜂电   1.大华   2.科技侠   3.果加
                    if (InteMap.get("Intelligent").toString().equals("2")){
                        String DeviceLockToken=redisUtils.get("DeviceLockToken");
                        //如果获取不到就重新登录
                        if (DeviceLockToken==null){
                            Map<String,Object> tokenMap=new HashMap<String, Object>();
                            params.put("client_id", InteDeviceLockConfig.CLIENT_ID);
                            params.put("client_secret",InteDeviceLockConfig.CLIENT_SECRET);
                            params.put("grant_type",InteDeviceLockConfig.GRANT_TYPE_PASSWORD);
                            params.put("username",InteDeviceLockConfig.USERNAME);
                            params.put("password",InteDeviceLockConfig.PASSWORD);
                            params.put("redirect_uri",InteDeviceLockConfig.REDIRECT_URL);
                            tokenMap= InteDeviceLockUtil.oauth2Token(params);
                            if (tokenMap.get("access_token")!=null){
                                DeviceLockToken=tokenMap.get("access_token").toString();
                                //token存到redis中
                                redisUtils.set("DeviceLockToken",DeviceLockToken,Long.valueOf(tokenMap.get("expires_in").toString()));
                            }else{
                                result.putFailed("token获取失败");
                            }
                        }


                        Map<String,Object> UnAauthMap = new HashMap<>();
                        UnAauthMap.put("clientId", InteDeviceLockConfig.CLIENT_ID);//应用编号
                        UnAauthMap.put("accessToken",DeviceLockToken);//访问令牌
                        UnAauthMap.put("lockId",InteMap.get("Identifier"));//锁编号
                        UnAauthMap.put("keyId",InteMap.get("CodeId"));//钥匙编号
                        UnAauthMap.put("date",InteDeviceLockUtil.getTimeSign());//当前时间(毫秒数)

                        Map<String,Object>   UnAauthMapResult = InteDeviceLockUtil.keyUnauthorize(UnAauthMap);
                        if (UnAauthMapResult.get("errcode")!=null && UnAauthMapResult.get("errcode").toString().equals("0")){
                            result.putSuccess("解除科技侠智能门锁蓝牙成功");

                            //改为键盘密码,
                            Map<String,Object> sendMap = new HashMap<>();
                            sendMap.put("clientId", InteDeviceLockConfig.CLIENT_ID);//应用编号
                            sendMap.put("accessToken",DeviceLockToken);//访问令牌
                            sendMap.put("lockId",InteMap.get("Identifier"));//智能设备编号
                            sendMap.put("keyboardPwdVersion","4");//键盘密码版本, 三代锁的密码版本为4
                            sendMap.put("keyboardPwdType","3");//参数值 单次	1
                            //密码有效时间
                            sendMap.put("startDate",InteDeviceLockUtil.getTimeSign());
                            //获取结束时间
                            //sendMap.put("endDate",InteDeviceLockUtil.getTimeSign(InteDeviceLockUtil.getTimeAfter(System.currentTimeMillis(),2*60*60*1000,"yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd HH:mm:ss"));
                            sendMap.put("endDate",InteDeviceLockUtil.getTimeSign(DateUtils.format(DateUtils.addDateMonths( DateUtils.stringToDate(params.get("EndTime").toString(),"yyyy-MM-dd"),0))+InteDeviceLockConfig.LOCK_TIME_END,"yyyy-MM-dd HH:mm:ss"));



                            sendMap.put("date",InteDeviceLockUtil.getTimeSign());
                            Map<String,Object> sendMapResult = InteDeviceLockUtil.keyboardPwdGet(sendMap);
                            if (sendMapResult.get("keyboardPwdId")!=null && !sendMapResult.get("keyboardPwdId").toString().equals("")){
                                result.putSuccess("发送键盘密码成功");
                                InteMap.put("keyboardPwd",sendMapResult.get("keyboardPwd")); //键盘密码
                                InteMap.put("CodeId",sendMapResult.get("keyboardPwdId"));//键盘密码id

                            }else {
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                result.putFailed(sendMapResult.get("errmsg").toString());

                            }
                        }else{
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            result.putFailed(UnAauthMapResult.get("errmsg").toString());
                        }


                    }else if(InteMap.get("Intelligent").toString().equals("3")){//果加
                        String GuoJiaToken=redisUtils.get("GuoJiaToken");
                        //如果获取不到就重新登录
                        if (GuoJiaToken==null){
                            Map<String,Object> guoJiaMap=new HashMap<String, Object>();
                            guoJiaMap.put("s_id", InteGuoJiaUtil.getSid());
                            guoJiaMap.put("version","1");
                            JSONObject bodyJson=new JSONObject();
                            //key
                            DESEncrypt desPlus2 = new DESEncrypt(InteGuoJiaConfig.DES_KEY);
                            //密码
                            bodyJson.put("account",InteGuoJiaConfig.ACCOUNT);
                            bodyJson.put("password",desPlus2.encrypt(InteGuoJiaConfig.PASSWORD));
                            guoJiaMap= InteGuoJiaUtil.login(guoJiaMap,bodyJson);
                            //返回的token数据
                            Map<String,Object>dataMap=(Map<String,Object>)guoJiaMap.get("data");
                            if (guoJiaMap.get("rlt_code").toString().equals("HH0000")){//HH0000 、成功
                                GuoJiaToken=dataMap.get("access_token").toString();
                                //token存到redis中
                                redisUtils.set("GuoJiaToken",GuoJiaToken,Long.valueOf(dataMap.get("expires_second").toString()));
                            }else{
                                result.putFailed("token获取失败");
                            }
                        }
                        //先解除果加的门锁授权在重新授权
                        Map<String,Object> headParams=new HashMap<String, Object>();
                        headParams.put("s_id",InteGuoJiaUtil.getSid());
                        headParams.put("version","1");
                        headParams.put("access_token",GuoJiaToken);

                        JSONObject bodyJsonOne=new JSONObject();
                        bodyJsonOne.put("lock_no",InteMap.get("Identifier"));//门锁编码
                        bodyJsonOne.put("mobile",params.get("phone"));
                        Map<String,Object> JieChuMap = InteGuoJiaUtil.lockCancel_auth(headParams,bodyJsonOne);
                        if (JieChuMap.get("rlt_code") !=null && JieChuMap.get("rlt_code").toString().equals("HH0000")){//HH0000 、成功
                        result.putSuccess("解除门锁授权成功");

                            //发送离线时效密码
                            JSONObject pwdAdd=new JSONObject();
                            pwdAdd.put("lock_no",InteMap.get("Identifier"));//门锁编码
                            Date dayss = new Date();
                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                            pwdAdd.put("valid_time_start",InteDeviceLockUtil.getTimeSign(DateUtils.format(DateUtils.addDateMonths( DateUtils.stringToDate(df.format(dayss),"yyyy-MM-dd"),0))+InteDeviceLockConfig.LOCK_TIME_START,"yyyy-MM-dd HH:mm:ss"));//开始时间
                            pwdAdd.put("valid_time_end",InteDeviceLockUtil.getTimeSign(DateUtils.format(DateUtils.addDateMonths( DateUtils.stringToDate(params.get("EndTime").toString(),"yyyy-MM-dd"),0))+InteDeviceLockConfig.LOCK_TIME_END,"yyyy-MM-dd HH:mm:ss"));
                            pwdAdd.put("pwd_user_mobile",params.get("phone"));//手机号
                            Map<String,Object> guoJiaResult=InteGuoJiaUtil.pwd_offlineadd(headParams,pwdAdd);

                            DESEncrypt desPlus2 = new DESEncrypt(InteGuoJiaConfig.DES_KEY);
                            String d2="";
                            String pwd_no="";
                            try {
                                Map<String,Object> dataMap=(Map<String,Object>)guoJiaResult.get("data");
                                d2 = desPlus2.decrypt(DESEncrypt.byteArr2HexStr(DESEncrypt.hexStringToBytes(dataMap.get("pwd_text").toString())));
                                pwd_no = dataMap.get("pwd_no").toString();
                            }catch (Exception e){
                                log.debug("键盘密码解密错误"+e);
                            }

                            if (guoJiaResult.get("rlt_code").toString().equals("HH0000")){//HH0000 请求成功
                                InteMap.put("CodeId",pwd_no);//钥匙id
                                InteMap.put("keyboardPwd",d2);//钥匙内容

                            }else{
                                return result.putFailed("服务器繁忙");
                            }


                        }else{
                            result.putFailed(JieChuMap.get("rlt_msg").toString());
                        }

                    }
                }

                log.info("11111111111111111111111");
                log.info("identifierList"+identifierList);
                //保存本次密码id,并修改合同表密码类型为密码开门
                StringBuffer IntelligentRoomBuffer = new StringBuffer();


                 StringBuffer keyword3Buffer = new StringBuffer();
                for (Map<String,Object> map6:identifierList) {//测试map,保存本次签约门锁的密码
                    for (Map<String,Object> map5:epcIdenList) {

                    if((MapUtils.getString(map6,"Identifier")!=null&&MapUtils.getString(map5,"Identifier")!=null&&MapUtils.getString(map6,"Identifier").equals(MapUtils.getString(map5,"Identifier")))){
                        map6.putAll(map5);
                        }
                    }
                    }

                for (Map<String,Object> map4:identifierList){//测试map,保存本次签约门锁的密码
                    if (MapUtils.getString(map4,"CodeId")!=null||!MapUtils.getString(map4,"CodeId").equals("")) {
                        IntelligentRoomBuffer.append(MapUtils.getString(map4, "Identifier")).append(":").append(MapUtils.getString(map4, "CodeId")).append(",");
                    }

                    if (MapUtils.getInteger(map4,"HouConType")==1){
                        weiMap.put("keyword2",new TemplateData(map4.get("keyboardPwd").toString(), "#4876FF"));
                    }else if(MapUtils.getInteger(map4,"HouConType")==2){
                        keyword3Buffer.append(MapUtils.getString(map4,"HouConName")).append(":");
                        keyword3Buffer.append(MapUtils.getString(map4,"keyboardPwd")).append(";");
                    }

                }
                weiMap.put("keyword3",new TemplateData(keyword3Buffer.toString(), "#4876FF"));
                //发送短信推送
                Jsapi_ticketUtil.sendTemplate(params.get("openid").toString(), WeChatConfig.SEND_KEY,"","#4876FF", net.sf.json.JSONObject.fromObject(weiMap));

                log.info("修改合同表里面的智能门锁密码");
                log.info("IntelligentRoom"+IntelligentRoomBuffer.toString());

                //修改合同表里面的智能门锁编号,并且修改类型
                Map<String,Object> PactUpMap = new HashMap<>();
                PactUpMap.put("term","1");//1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                PactUpMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(PactUpMap);
                PactUpMap.put("IntelligentRoom",IntelligentRoomBuffer.toString());
                PactUpMap.put("IntelligentOpenType",1);
                PactUpMap.put("PaId",params.get("PaId"));
                 Integer coutt = tenRoomMapper.updateRoomType(PactUpMap);
                 if (coutt>0){
                      result.putSuccess("修改合同表成功");

                 }else {
                     return result.putFailed("修改合同表失败");
                 }

            }
        } catch (NoTransactionException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {

            lock.unlock();
        }

        return result;

    }
}
